package com.xc.freeapp.common;

import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
/**
 * 读取消息配置文件信息
 * @author Zhouxinjie
 * 
 */

public class MsgConfig {

	private static Map<String, String> msgs;
	private static Logger log = Logger.getLogger(MsgConfig.class);
	private static Map<String, Map<String, String>> msgCache = new HashMap<String, Map<String, String>>();

	static {
		msgs = new HashMap<String, String>();
		try {
			ResourceBundle bundle = ResourceBundle.getBundle("messages");
			Enumeration<String> keys = bundle.getKeys();

			while (keys.hasMoreElements()) {
				String key = keys.nextElement();
				msgs.put(key, bundle.getString(key));
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error("msg 初始化失败!", e);
		}
	}

	public static String getMsg(String code) {
		if (code == null || code.isEmpty())
			return null;
		return msgs.get(code);
	}

	public static String getMsg(String code, Object... params) {
		String pattern = getMsg(code);
		String msg = MessageFormat.format(pattern, params);
		return msg;
	}

	public static String getMsg(String path, String key) {
		Map<String, String> oldMap = msgCache.get(path);
		if (oldMap != null) {
			String value = oldMap.get(key);
			if (value != null)
				return value;
		}

		try {
			ResourceBundle bundle = ResourceBundle.getBundle(path);
			Enumeration<String> keys = bundle.getKeys();
			Map<String, String> newMsg = new HashMap<String, String>();
			while (keys.hasMoreElements()) {
				String _key = keys.nextElement();
				newMsg.put(_key, bundle.getString(_key));
				if (log.isDebugEnabled()) {
					log.debug("消息key:" + key + ";msg:" + bundle.getString(key));
				}
				msgCache.put(path, newMsg);
				return newMsg.get(key);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("msg 初始化失败!", e);
		}

		return null;
	}

	public static void main(String[] args) {

		System.out.println(MsgConfig.getMsg("900"));
		System.out.println(MsgConfig.getMsg("test","名称","值"));
	}
}
